package ejb.forecast;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;

import org.jboss.ejb3.annotation.ResourceAdapter;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import ejb.dao.PositionDAO;
import ejb.dao.UserDAO;
import ejb.entity.City;
import ejb.entity.DefaultCity;
import ejb.entity.Forecast;
import ejb.entity.Position;
import ejb.entity.User;
import ejb.manager.CityManager;
import ejb.manager.ForecastManager;
import ejb.manager.MailManager;

@ResourceAdapter("quartz-ra.rar")
@MessageDriven(activationConfig = {
		@ActivationConfigProperty(propertyName="cronTrigger", propertyValue="0 0 13 * * ?")	
	}, messageListenerInterface=Job.class)
public class EmailForecast implements Job{
	@EJB
	private UserDAO userDAO;
	@EJB
	private PositionDAO positionDAO;
	@EJB
	private ForecastManager forecastManager;
	@EJB
	private MailManager mailManager;
	@EJB
	private CityManager cityManger;
	
	@Override
	public void execute(JobExecutionContext arg0) {
		System.out.println("PDF dla usera.");
		List<User> users = userDAO.getUsers();
		List<City> forecastedBasicCities = new ArrayList<City>();
		//prognoza miast z bazy
		List<City> allCities = cityManger.getAllCities(); 
		for(City city : allCities){
			List<Forecast> forecast = city.getForecasts();
			City forecastedCity = new DefaultCity();
			forecastedCity.setName(city.getName());
			forecastedCity.setConditions(forecast.get(0).getConditions());
			forecastedCity.setTemperature(forecast.get(0).getTemperature());
			forecastedBasicCities.add(forecastedCity);
		}
		
		for(User u : users){
			List<Position> userPositions = positionDAO.findByUserAndForecast(u, true);
			List<City> forecastedCities = new ArrayList<City>();
			if(u.isForecast()) forecastedCities.addAll(forecastedBasicCities);
			for(Position position : userPositions){
				City forecastCity = forecastManager.getPositionForecast(position, 1);
				forecastedCities.add(forecastCity);
			}
			if(forecastedCities.size() > 0) mailManager.send(u.getEmail(), forecastedCities);
			forecastedCities.removeAll(forecastedCities);
		}
	}
}
